/* Sentinel - IRC Statistical and Operator Services
** converttld.c - Convert old GeoStats or NeoStats style TLD files to the
**                new style tab delimited Sentinel TLD files.
**
** Copyright W. Campbell and others.  See README for more details
** Some code Copyright: Jonathan George, Kai Seidler, ircd-hybrid Team,
**                      IRCnet IRCD developers.
**
** $Id: converttld.c 7 2010-02-01 19:17:42Z dubkat $
*/

#include <string.h>
#include <stdio.h>

#define BUFSIZE 512

int main(int argc, char *argv[])
{
  char buf1[BUFSIZE];
  char buf2[BUFSIZE];
  int i;
  char *tmp = NULL;
  char *tmp2 = NULL;
  FILE *fp;
  FILE *new;

  if (argc < 2)
  {
    fprintf(stderr, "Syntax:  %s <from file> <to file>\n", argv[0]);
    exit(1);
  }

  if (argc == 2)
  {
    fprintf(stderr, "Defaulting to STDOUT\n");
  }

  if ((fp = fopen(argv[1], "r")) == NULL)
  {
    fprintf(stderr, "Unable to open %s for reading\n", argv[2]);
    exit(2);
  }

  if ((argc == 3) && (new = fopen(argv[2], "w")) == NULL)
  {
    fprintf(stderr, "Unable to open %s for writing\n", argv[3]);
    exit(3);
  }

  if (new == NULL)
  {
    new = stdout;
  }

  while (fgets(buf1, BUFSIZE, fp))
  {
    memcpy(buf2, buf1, sizeof(buf1));
    /* This code pulls the tld part out of the original
    ** string, then removes the last ')' and the '\n'
    */
    tmp = strrchr(buf1, '(');
    tmp++;
    /* trim two characters unconditionally */
    tmp[strlen(tmp) - 1] = '\0';
    tmp[strlen(tmp) - 1] = '\0';
    for (i = 0; buf1[i] != '('; i++)
      buf2[strlen(buf2) + 1] = buf1[i];

    if ((tmp2 = strchr(buf2, '\n')))
      * tmp2 = '\0';

    /* Unlike in Sentinel, we want to REMOVE the last (tld)
    ** part
    */
    if ((tmp2 = strrchr(buf2, '(')))
    {
      tmp2--;
      *tmp2 = '\0';
    }

    fprintf(new, "%s\t%s\n", tmp, buf2);
  }

  fclose(fp);
  fclose(new);
}
